/**profile中保存用户的各种信息，比如userName, token等 */

import axios from "axios";

class Profile {
    constructor() {
        this.$ready = false;
        axios
            .get(`/users/profile?v=${Date.now()}`)
            .then((res) => {
                if (res.data && res.data.data) {
                    this.$ready = true;
                    this.profile = res.data.data;
                    if (this.readycbs) {
                        this.readycbs.map((cb) => cb());
                        this.readycbs = null;
                    }
                }
            })
            .catch((err) => {
                console.log("err: ", err);
            });
    }

    ready(cb) {
        if (this.$ready) {
            cb();
        } else {
            this.readycbs = this.readycbs || [];
            this.readycbs.push(cb);
        }
    }

    get isLogin() {
        return this.$ready && this.profile && !!this.profile.token;
    }

    get userName() {
        return this.isLogin ? this.profile.userName : "";
    }

    get token() {
        return this.isLogin ? this.profile.token : "";
    }

    get nick() {
        return this.isLogin ? this.profile.nick : "";
    }

    get gMoney() {
        return this.isLogin ? this.profile.gMoney : "";
    }
}

const profile = new Profile();

export default profile;
